<template>
  <div class="refine_inpublish">
    <h2 class="titleblue">{{cno}}内网公告</h2>
    <div class="contant">
      <el-form ref="form" :model="form" label-width="90px">
        <el-row :gutter="24">
          <el-form-item label="公告类型">
            <el-select :disabled="detail=='look'?true:false" v-model="form.type" class="select-width-220"
                       @change='changeType'>
              <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
            <el-radio-group v-model="form.teamgroup" v-if='level'>
              <div class="selectli" v-for="(item,index) in typeclr" :key="index">
                <el-radio-button :disabled="detail=='look'?true:false" :label="item.level">
                  <div class="bgcolor" :style="{'background-color': item.bgcolor}"></div>
                </el-radio-button>
              </div>
            </el-radio-group>
          </el-form-item>
        </el-row>
        <el-row :gutter="24">
          <el-form-item label="公告主题">
            <el-input :disabled="detail=='look'?true:false" v-model="form.title" class="input-width-460"></el-input>
          </el-form-item>
        </el-row>
        <el-row :gutter="24" class="checkgroup">
          <el-form-item label="发文至">
            <el-checkbox v-model="checkAll" @change="handleCheckAllChange" style="display: block;">全选</el-checkbox>
            <div class="sendDiv" v-for="(item,index) in sendTos" :key='index'>
              <el-checkbox :disabled="detail=='look'?true:false" :label="item.id" name="tpallot" v-model='item.choose'>
                {{item.name}}
              </el-checkbox>
            </div>
          </el-form-item>
        </el-row>

        <el-row :gutter="24">
          <el-form-item label="公告正文">
            <el-input :disabled="detail=='look'?true:false" type="textarea" v-model="form.content"></el-input>
          </el-form-item>
        </el-row>
        <el-row>
          <el-col :span="24" v-if='cno=="查看"&&form.attachments||cno=="编辑"&&form.attachments'>
            <div class="grid-content">
              <el-form-item label='已上传附件'>
                <div class="annex-width">
                  <a class="annex-div" v-for='(item,index) in bgImg' target='_blank' @mouseover="onMouseOver(index)"
                     @mouseout="onMouseOut()"
                     :href="item.url" download="">
                    <!-- <a class="annex-div"> -->
                    <img :src="item.url"/>
                    <div class="annext-modal" v-show="active==index">
                      <div class="mask"></div>
                      <img src="@/assets/dowload-icon.png"/>
                    </div>
                  </a>
                  <a class="annex-div file-div" v-for='(item,index) in fileImg' target='_blank' :href="item.url"
                     download="item">
                    <div>{{item.name}}</div>
                  </a>
                </div>
              </el-form-item>
            </div>
          </el-col>
        </el-row>

        <el-row :gutter="24" style="width:460px;" v-if='cno!="查看"'>
          <el-form-item label="附件">
            <el-upload class="upload-demo"
                       :action="$config.FILE_UPLOAD_URL"
                       :data='uploadobj'
                       :on-preview="handlePreview"
                       :on-remove="uploadRemove"
                       :before-upload="beforeRemove"
                       :file-list="fileList"
                       :limit="6"
                       accept=''
                       :headers="headers"
                       :on-success='uploadSuccess'
                       :on-exceed="handleExceed"
                       :disabled="detail=='look'?true:false">
              <el-button size="small" type="primary" :disabled="detail=='look'?true:false">上传</el-button>
              <div slot="tip" class="el-upload__tip">上传附件</div>
            </el-upload>
          </el-form-item>
        </el-row>
        <el-row :gutter="24" v-if="detail=='look'">
          <el-form-item label="公告来源">
            <el-input v-model="form.name" class="select-width-220"></el-input>
          </el-form-item>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="10" style="padding:0;">
            <el-form-item label="开始时间">
              <el-date-picker v-model="form.publishBeginTime" align="right" type="datetime" placeholder="选择日期"
                              value-format='yyyy-MM-dd HH:mm:ss'
                              :picker-options="pickerOptions1" :disabled="detail=='look'?true:false">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="结束时间">
              <el-date-picker v-model="form.publishEndTime" align="right" type="datetime" placeholder="选择日期"
                              value-format='yyyy-MM-dd HH:mm:ss'
                              :picker-options="pickerOptions2" :disabled="detail=='look'?true:false">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" style="text-align: center;" v-if='cno!="查看"' class="footer-row">
          <el-form-item>
            <el-button @click="creatsure" class="sure">发布</el-button>
            <el-button @click="creatcancel" class="cancel">取消</el-button>
          </el-form-item>
        </el-row>
        <el-row :gutter="24" style="text-align: center;" v-if='cno=="查看"' class="footer-row">
          <el-form-item>
            <el-button @click="last" class="sure">上一篇</el-button>
            <el-button @click="next" class="cancel">下一篇</el-button>
          </el-form-item>
        </el-row>
      </el-form>
    </div>
  </div>
</template>

<script>
  import * as orgService from '@/services/OrganizationService'
  import * as noticeService from '@/services/NoticeService'
  import dictionaryService from '@/services/DictionaryService'
  import moment from 'moment'
  export default {
    props: ["detail"],
    data: function () {
      return {
        checkAll: true,
        isIndeterminate: true,
        form: {
          type: '',
          teamgroup: 'red',
          title: '',
          content: '',
          publishBeginTime: '',
          publishEndTime: '',
          url: "",
        },
        cno: '发布',
        level: false,
        sendTos: [],
        options: [],
        bgImg: [],
        fileImg: [],
        page: 0,
        active: -1,
        next1: '',
        last1: '',
        type1: '',
        typeclr: [{
          level: 'red',
          bgcolor: '#e51c23'
        },
          {
            level: 'orange',
            bgcolor: '#fab505'
          },
          {
            level: 'yellow',
            bgcolor: '#fcff16'
          },

          {
            level: 'blue',
            bgcolor: '#5bd3ff'
          }
        ],

        pickerOptions1: {
          disabledDate(time) {
            return time.getTime() < Date.now() - 8.64e7;

          },
          shortcuts: [{
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date());
            }
          }, {
            text: '昨天',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit('pick', date);
            }
          }, {
            text: '一周前',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', date);
            }
          }]
        },
        pickerOptions2: {
          disabledDate(time) {
            return time.getTime() < Date.now() - 8.64e7;

          },
          shortcuts: [{
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date());
            }
          }, {
            text: '昨天',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit('pick', date);
            }
          }, {
            text: '一周前',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', date);
            }
          }]
        },
        uploadobj: {
          filename: '',
          mimeType: "image/jpeg",
          bus: 'notice'
        },
        headers: {
          Authorization: 'Bearer ' + localStorage.getItem('token')
        },
        fileList: [],
      };
    },
    created() {
      if (!this.$route.query.type) {
        this.form.publishBeginTime = moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
      }
    },
    async mounted() {
      let options = await dictionaryService.find('GGLX');

      this.options = options.map((option) => {
        return {
          "label": option.name,
          'value': option.id
        }
      });
      orgService.findAll().then((orgList) => {
        orgList.data.forEach((item, i) => {
          this.sendTos.push({
            name: item.name,
            choose: true,
            id: item.id
          })
        })
      });
      if (this.$route.query.type == 'edit') {
        this.cno = '编辑'
        this.getData()
      } else if (this.$route.query.type == 'look') {
        this.cno = '查看'
        this.lookGetData()
      }
    },
    methods: {
      //  发文至 全选功能
      handleCheckAllChange () {
          let falgB = true
          if (this.isIndeterminate) {
              falgB = false
          }
        this.sendTos.forEach((item, index) => {
            this.$set(this.sendTos[index], 'choose', falgB)
        })
        // this.checkAll = !this.checkAll
        this.isIndeterminate = !this.isIndeterminate
      },
      lookGetData(str, page) {
        this.bgImg = [];
        this.fileImg = [];
        if (!page) {
          this.page = (10 * parseInt(this.$route.query.pageNum - 1)) + parseInt(this.$route.query.index);
        }
        noticeService.noticeList({size: 1, page: this.page, query: this.$route.query.searchUrl}).then((res) => {
          if (res.data.length === 0) {
            this.$alert(str);
            if (str === '没有下一篇了') {
              this.$alert('没有下一篇了');
              this.page -= 1;
              this.lookGetData('没有下一篇了', this.page);
            }
          }
          this.fileList = [];
          this.type1 = res.data[0].type;
          this.form = res.data[0];
          this.form.publishBeginTime = moment(res.data[0].publishBeginTime).format('YYYY-MM-DD HH:mm:ss');
          this.form.publishEndTime = moment(res.data[0].publishEndTime).format('YYYY-MM-DD HH:mm:ss');
          this.form.teamgroup = res.data[0].noticeGrade;
          var arr = JSON.parse(res.data[0].sendToUser);
            var falgNum = 0
          for (let j of this.sendTos) {
            j.choose = false;
            for (var i of arr) {
              if (i === j.id) {
                j.choose = true
                  falgNum ++
              }
            }
          }
            if (falgNum < this.sendTos.length) {
                this.isIndeterminate = false
            }
          if (res.data[0].attachments) {
            var newarr = JSON.parse(res.data[0].attachments);
            for (var x of newarr) {
              if (x.name.lastIndexOf('jpeg') != -1 || x.name.lastIndexOf('png') != -1 || x.name.lastIndexOf('jpg') != -1) {
                this.bgImg.push(x)
              } else {
                this.fileImg.push(x);
              }
              this.fileList.push(x)
            }
          }
        });
      },
      changeType(val) {
        if (val == 143) {
          this.level = true
        } else {
          this.level = false
        }
      },
      getData() {
        this.bgImg = [];
        this.fileImg = [];
        noticeService.getOneNotice(this.$route.query.id).then((res) => {
          this.fileList = [];
          this.type1 = res.type;
          this.form = res;
          this.form.publishBeginTime = moment(res.publishBeginTime).format('YYYY-MM-DD HH:mm:ss');
          this.form.publishEndTime = moment(res.publishEndTime).format('YYYY-MM-DD HH:mm:ss');
          this.form.teamgroup = res.noticeGrade;
          var arr = JSON.parse(res.sendToUser);
          var falgNum = 0
          for (let j of this.sendTos) {
            j.choose = false;
            for (var i of arr) {
              if (i === j.id) {
                j.choose = true
                falgNum ++
              }
            }
          }
          if (falgNum < this.sendTos.length) {
              this.isIndeterminate = false
          }
          if (res.attachments) {
            var newarr = JSON.parse(res.attachments);
            for (var x of newarr) {
              if (x.name.lastIndexOf('jpeg') != -1 || x.name.lastIndexOf('png') != -1 || x.name.lastIndexOf('jpg') != -1) {
                this.bgImg.push(x)
              } else {
                this.fileImg.push(x.name.slice(x.name.lastIndexOf("/") + 1));
                // this.fileImg.push(x);
              }
              this.fileList.push(x)
            }
          }
        });
        // this.$axios.get(this.$config["noticeDetail"], {
        //   params: {
        //     skey: localStorage.getItem('auth'),
        //     d_id: this.$route.query.id,
        //     type:this.$route.query.type1,
        //     title:this.$route.query.title,
        //   }
        // }).then((res) => {
        //   this.fileList=[]
        //   this.type1=res.data.content[0].type
        //   this.form = res.data.content[0]
        //   this.next1=res.data.content[0].next;
        //   this.last1=res.data.content[0].last;
        //   this.form.teamgroup = res.data.content[0].noticeGrade
        //   var arr = JSON.parse(res.data.content[0].sendTo)
        //   for (var j of this.sendTos) {
        //     j.choose = false
        //     for (var i of arr) {
        //       if (i == j.id) {
        //         j.choose = true
        //       }
        //     }
        //   }
        // })
      },
      handleRemove(file, fileList) {
      },
      handlePreview(file) {
      },
      uploadSuccess(res) {
        this.fileList.push({name: res.data.name, url: res.data.link})
      },
      uploadRemove: function (res) {
        // var deleteItem = res.response.resourceInfo.systemFileName;
        var deleteItem = res.name
        for (var n = 0; n < this.fileList.length; n++) {
          if (this.fileList[n].name.indexOf(deleteItem) != -1) {
            this.fileList.splice(n, 1);
          }
        }
      },
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 6 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },
      beforeRemove(file) {
        var tpye = file.name.slice(file.name.lastIndexOf(".") + 1)
        if (tpye == "jpeg" || tpye == 'jpg' || tpye == 'png') {
          this.uploadobj.mimeType = 'image/jpeg'

        } else if (tpye == 'doc' || tpye == 'docx') {
          this.uploadobj.mimeType = 'application/msword'
        } else if (tpye == 'pdf') {
          this.uploadobj.mimeType = 'application/pdf'
        } else if (tpye == 'txt') {
          this.uploadobj.mimeType = 'text/plain'
        }
        this.uploadobj.filename = file.name
        return true;
      },
      creatsure() {
        let unitArr = [];
        for (var n of this.sendTos) {
          if (n.choose == true) {
            unitArr.push(n.id);
          }
        }
        let sendTo = unitArr;
        let url = [];
        for (var n of this.fileList) {
          url.push({name: n.name, url: n.url});
        }
        let startTime;
        let endTime;
        if (this.level == false) {
          var noticeGrade = 'white'
        } else {
          var noticeGrade = this.form.teamgroup
        }
        if (this.form.type == 0) {
          this.$alert('请选择公告类型', '提示');
          return false;
        }
        if (this.form.title == 0) {
          this.$alert('请输入公告主题', '提示');
          return false;
        }
        // if (this.form.content == 0) {
        //   this.$alert('请输入公告正文', '提示');
        //   return false;
        // }
        if (!this.form.publishBeginTime) {
          this.$alert('请选择开始时间', '提示');
          return false;
        } else {
          startTime = new Date(this.form.publishBeginTime)
        }
        if (this.form.publishEndTime) {
          endTime = new Date(this.form.publishEndTime)
        }
        // if (this.form.publishEndTime.length == 0) {
        //     this.$alert('请选择结束时间', '提示');
        //     return false;
        // }
        if (this.$route.query.type == 'edit') {
          var params = {
            id: this.form.id,
            title: this.form.title,
            noticeGrade: noticeGrade,
            content: this.form.content.trim(),
            publishBeginTime: startTime,
            publishEndTime: endTime,
            sendToUser: JSON.stringify(sendTo),
            type: this.form.type,
            typeName: this.options.find(o => o.value === this.form.type).label,
            releaseFlag: true,
            intranetFlag: true,
            pushFlag: false,
            source: this.$profile.organiza.name,
            attachments: JSON.stringify(url),
            createTime: this.form.createTime,
            //url: url.join(","),
            //skey: localStorage.getItem('auth'),
          }
          noticeService.updateNotice(params).then((res) => {
            this.$alert('编辑成功', {
              callback: action => {
                this.form = {};
                this.fileList = [];
                this.$emit("close");
                this.boradIndex();
              }
            });
          })
        } else {
          var params = {
            title: this.form.title,
            noticeGrade: noticeGrade,
            content: this.form.content,
            publishBeginTime: startTime,
            publishEndTime: endTime,
            sendToUser: JSON.stringify(sendTo),
            type: this.form.type,
            typeName: this.options.find(o => o.value === this.form.type).label,
            releaseFlag: true,
            intranetFlag: true,
            pushFlag: false,
            source: this.$profile.organiza.name,
            attachments: JSON.stringify(url),
            //url: url.join(","),
            //skey: localStorage.getItem('auth'),
          }
          noticeService.createNotice(params).then(() => {
            this.$alert('发布成功', {
              callback: action => {
                this.form = {};
                this.fileList = [];
                this.$emit("close");
                this.boradIndex();
              }
            });
          });
        }
      },
      creatcancel() {
        this.$emit("close");
      },
      onMouseOver(id) {
        this.active = id;
      },
      boradIndex() {
        this.$root.eventHub.$emit('boradIndex')
      },
      onMouseOut() {
        this.active = -1;
      },
      next() {
        this.page = this.page + 1;
        this.lookGetData('没有下一篇了', this.page);
      },
      last() {
        this.page = this.page - 1;
        if (this.page < 0) {
          this.$alert('没有上一篇了');
          this.lookGetData();
        } else {
          this.lookGetData('没有上一篇了', this.page);
        }
      }
    }
  };

</script>
<style lang='scss'>

  .refine_inpublish {
    width: 100%;
    display: inline-block;

    .el-row {
      margin-left: 0 !important;
      margin-right: 0 !important;
    }
    .selectli {
      float: left;
      margin-left: 20px;
      width: 22px;
      height: 22px;
    }
    .selectli .el-radio-button__inner {
      width: 16px;
      height: 16px;
      padding: 0;
      background: none;
      border: 0px;
      margin: 2px;
    }
    .sendDiv {
      float: left;
      margin-right: 15px;
    }
    .is-active {
      border: solid 1px #b3b3b3;
      width: 22px;
      height: 22px;
    }
    .bgcolor {
      width: 16px;
      height: 16px;
    }
    .el-select select {
      border-radius: 2px;
      border: solid 1px #dddddd;
    }
    .el-input input {
      border-radius: 2px;
      border: solid 1px #dddddd;
    }
    .input-width-460 input {

    }
    .checkgroup .el-form-item__content {
      width: 90%;
      border: 1px solid #ddd;
      padding: 10px;
      box-sizing: border-box;
    }
    .checkgroup .el-form-item {
      width: 100%;
    }
    .el-textarea textarea {
      height: 86px;
      border-radius: 2px;
      border: solid 1px #dddddd;
      padding: 10px;
    }
    .el-upload--text {
      float: right;
      width: 58px;
      height: 40px;
      border: none;
      border-radius: 2px;
      margin-left: 5px;

      button {
        background-color: #0062cd;
        border-radius: 2px;
        border: none;
        padding: 0;
        width: 58px;
        height: 40px;

      }
    }
    .el-upload__tip {
      width: 300px;
      height: 40px;
      border-radius: 2px;
      border: solid 1px #dddddd;
      float: left;
      margin-top: 0;
      padding: 0 15px;
      font-size: 14px;
      color: #b9b9b9;
      text-align: left;
    }
    .el-upload-list__item.is-success .el-upload-list__item-status-label {
      display: block;
      margin-top: 28px;
      margin-top: -5px;
    }
    .el-upload-list__item:first-child {
      margin-top: 0;
    }
    .el-date-editor {
      border-radius: 2px;
    }
    .sure {
      width: 110px;
      height: 36px;
      background-color: #0062cd;
      border-radius: 4px;
      padding: 0;
    }
    .cancel {
      width: 110px;
      height: 36px;
      border-radius: 4px;
      border: solid 1px #0062cd;
      padding: 0;
      color: #0062cd;
    }
    .annex-width > .annex-div > img {
      width: 62px;
      height: 64px;
      border-radius: 2px;
      float: left;
      margin-right: 10px;
      cursor: pointer;
      position: absolute;
      margin-bottom: 20px;
    }
    .mask {
      position: absolute;
      width: 62px;
      height: 64px;
      background-color: #000 !important;
      opacity: 0.3;
      padding-left: 0 !important;
      top: 0;
      left: 0;
      border: 0px !important;
    }
    .annex-width {
      padding: 0 !important;
      background-color: transparent !important;
      border: 0px !important;
    }
    .annex-div {
      margin-right: 10px;
      width: 62px;
      height: 64px;
      display: block;
      float: left;
      position: relative;
    }
    .file-div {
      width: auto;
      height: auto;
      padding: 0px;
      /*color: #333;*/
      margin-left: 0px;
      margin-right: 10px;

    }

    .annext-modal {
      width: 62px;
      height: 64px;
      position: absolute;
      padding-left: 0 !important;
      text-align: center;
      background-color: transparent !important;
      text-align: center;
      line-height: 64px;
    }
    .annext-modal img {
      position: absolute;
      margin-right: 0;
      background-color: transparent;
      width: auto;
      height: auto;
      vertical-align: middle;
      border: none;
      top: 50%;
      margin-top: -11px;
      width: 23px;
      height: 21px;
      margin-left: -10px;
    }
    .footer-row .el-form-item__content {
      margin-left: 0px !important
    }
  }
</style>
